<?PHP	//header
include('config/config.php');
include('php/header.php');
require "php/functions.php";
?>        

<?PHP	//Connect to database
	$conn = mysql_connect($cfg["connection"]["host"], $cfg["connection"]["userName"], $cfg["connection"]["password"]) 
		or die ('Error Cannot Connect to MySQL');
	@mysql_select_db($cfg["connection"]["database"]) or die( "Unable to select database");
?>

<?PHP
	session_start();
	if (isset($_POST['submit'])) {
		if (isset($_FILES['datatxtfile'])) {
			$allowedExts = array("txt", "csv");
			$extension = end(explode(".", $_FILES["datatxtfile"]["name"]));
			if(in_array($extension, $allowedExts))
			{
				if ($_POST['type'] == "Inventory") uploadTxtData_Inventory($_FILES["datatxtfile"]["tmp_name"]);
				elseif ($_POST['type'] == "Transaction") {
					uploadTxtData_Transaction($_FILES["datatxtfile"]["tmp_name"]);
				}
			}
			else {
				$_SESSION['uploadFailed'] = 1;
			}
		}
	}
	if (isset($_SESSION['uploadFailed']))  {
		if ($_SESSION['uploadFailed'] == 1) echo("<div class=\"warning_box\">Upload Failed</div>");
		elseif ($_SESSION['uploadFailed'] == -1) echo("<div class=\"valid_box\">Upload Successful</div>");
		$_SESSION['uploadFailed'] = 0;
	}
?>

<h2>Upload CSV</h2>
	 <div class="form">
	 <form role="form" action="upload_csv.php" method="POST" id="UploadForm" class="niceform" enctype="multipart/form-data">
			<fieldset>
				<dl>
					<dt><label for="password">Password:</label></dt>
					<dd><input type="password" name="" id="" size="54" /></dd>
				</dl>
				<dl>
					<dt><label for="password">Re-type Password:</label></dt>
					<dd><input type="password" name="" id="" size="54" /></dd>
				</dl>
				<dl>
					<dt><label for="color">Select type</label></dt>
					<dd>
						<input type="radio" name="type" id="" value="Inventory" /><label class="check_label">Inventory</label>
						<input type="radio" name="type" id="" value="Transaction" /><label class="check_label">Transaction</label>
						<input type="radio" name="type" id="" value="ReStock" /><label class="check_label">ReStock</label>
					</dd>
				</dl>
				<dl>
					<dt>Upload a File:</dt>
					<dd><input type="file" name="datatxtfile" id="datatxtfile"/></dd>
				</dl>
				<dl>
					<dt><label for="comments">Message:</label></dt>
					<dd><textarea name="comments" id="comments" rows="5" cols="36"></textarea></dd>
				</dl>
				<dl>
					<dt><label></label></dt>
					<dd>
						<input type="checkbox" name="interests[]" id="" value="" /><label class="check_label">I agree to the <a href="#">terms &amp; conditions</a></label>
					</dd>
				</dl>
				<dl class="submit">
				<input type="submit" name="submit" id="submit" value="Submit" />
				</dl>
			</fieldset>
	 </form>
	 </div>  

<div class="pagination">
<?PHP	//footer
include('php/footer.php');
?>

<?PHP
function uploadTxtData_Inventory($filename){	
		$file = fopen( $filename, "r" ) or die ('ERROR: fopen()');
		if (!$file) {
			$_SESSION['uploadFailed'] = 1;
			return;
		}
		$tbl_name="item";	
		$result = mysql_query($query);
		
		$filesize = filesize( $filename );
		$filetext = fread( $file, $filesize );
		
		fclose( $file );
		$content = explode("\n", $filetext);
		foreach($content as $line)
		{
			list($name, $category, $manuf, $barcode, $costprice, $currentStock, $minStock, $bundleunit) = explode(":",$line);
			$name = db_escape_string($name);

			$query = "INSERT INTO $tbl_name (itemId, itemName, price, category, manufacturer, local_stock, minimum_stock, bundle_unit) 
						VALUES('".$barcode."', '".$name."', '".$costprice."', '".$category."', '".$manuf."', '".$currentStock."', '".$minStock."', '".$bundleunit."')
						ON DUPLICATE KEY UPDATE itemName = '".$name."', price = '".$costprice."', category = '".$category."', manufacturer = '".$manuf."', local_stock = '".$currentStock."', minimum_stock = '".$minStock."', bundle_unit = '".$bundleunit."';";
			$result = mysql_query($query);
			if ($result == 0) {
				$_SESSION['uploadFailed'] = 1;
				return;
			}
		}	
		$_SESSION['uploadFailed'] = -1;
	}
	
function uploadTxtData_Transaction($filename){
		$file = fopen( $filename, "r" ) or die ('ERROR: fopen()');
		if (!$file) {
			$_SESSION['uploadFailed'] = 1;
			return;
		}
	
		list($action, $shopID, $transactionDate) = explode("_", $_FILES["datatxtfile"]["name"]);

		$filesize = filesize( $filename );
		$filetext = fread( $file, $filesize );
		
		$tbl_name="local_transaction";	
		
		fclose( $file );
		$content = explode("\n", $filetext);
		foreach($content as $line)
		{
			list($barcode, $unitSold, $transactionDate) = explode(":",$line);
			if ($barcode == "") continue;
			$query = "INSERT INTO $tbl_name (itemId, tDate, shopId, unit_sold) 
						VALUES('".$barcode."', '".$transactionDate."', '".$shopID."', '".$unitSold."')
						ON DUPLICATE KEY UPDATE itemId = '".$barcode."', tDate = '".$transactionDate."', shopId = '".$shopID."', unit_sold = '".$unitSold."';";
			$result = mysql_query($query);
			if ($result == 0) {
				println($query);
				$_SESSION['uploadFailed'] = 1;
				return;
			}
		}	
		$_SESSION['uploadFailed'] = -1;
}
?>